package com.henry.util;

import com.baomidou.mybatisplus.annotation.TableField;
import com.henry.entity.Menu;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Henry
 * @date 2020/7/5 11:42
 */
public class MybatisPlusUtil<T> {


    public Map<String, Object> convert(T t) {
        Map<String, Object> map = new HashMap<>();
        try {

            Field[] fields = t.getClass().getDeclaredFields();
            if (fields != null) {
                for (Field field : fields) {
                    if (Modifier.isStatic(field.getModifiers())) {
                        continue;
                    }
                    if (!field.isAccessible()) {
                        field.setAccessible(true);
                    }

                    Object o = field.get(t);
                    if(o!=null){
                        TableField annotation = field.getAnnotation(TableField.class);
                        if (annotation != null) {
                            String value = annotation.value();
                            if (value != null) {
                                map.put(value, o);
                            }
                        }else{
                            map.put(field.getName(), o);
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.out.println(e);
        }

        return map;
    }

    public static void main(String[] args) {
        MybatisPlusUtil<Menu> mybatisPlusUtil = new MybatisPlusUtil<>();
        Menu menu = new Menu();
        menu.setCode("aaa");
        menu.setFunctionId(14141);
        menu.setCreateTime(LocalDateTime.now());

        Map<String, Object> map = mybatisPlusUtil.convert(menu);
        System.out.println(map);
    }
}
